<?php

use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;

class RolesController extends ControllerBase {

    /**
     * Index action
     */
    public function indexAction() {
        $roles = Roles::find();
        $this->view->roles = $roles;
    }

    /**
     * Edits a role
     *
     * @param string $id
     */
    public function editAction($id) {
        $role = Roles::findFirstById($id);
        $form = new RoleForm($role);
        if ($this->request->isPost()) {
            $name = $this->request->getPost('name');
            $note = $this->request->getPost('note');
            $role->name = $name;
            $role->note = $note;
            $role->save();
        }
        $this->view->form = $form;
    }

    /**
     * Creates a new role
     */
    public function createAction() {
        $form = new RoleForm();
        if ($this->request->isPost()) {
            $name = $this->request->getPost('name');
            $note = $this->request->getPost('note');
            $role = new Roles();
            $role->name = $name;
            $role->note = $note;
            if ($role->save()) {

                $this->flash->success("role was created successfully");

                return $this->dispatcher->forward(array(
                            "controller" => "roles",
                            "action" => "index"
                ));
            }
        }
        $this->view->form = $form;
    }

    /**
     * Deletes a role
     *
     * @param string $id
     */
    public function deleteAction($id) {

        $role = Roles::findFirstByid($id);
        if (!$role) {
            $this->flash->error("role was not found");

            return $this->dispatcher->forward(array(
                        "controller" => "roles",
                        "action" => "index"
            ));
        }

        if (!$role->delete()) {

            foreach ($role->getMessages() as $message) {
                $this->flash->error($message);
            }

            return $this->dispatcher->forward(array(
                        "controller" => "roles",
                        "action" => "search"
            ));
        }

        $this->flash->success("role was deleted successfully");

        return $this->dispatcher->forward(array(
                    "controller" => "roles",
                    "action" => "index"
        ));
    }

}
